from flask import Flask, request, jsonify, redirect

app = Flask(__name__)

app.config.from_pyfile("config.py")

user_list = []
blog_list = [{"title": "我是好人", "author": "柴进"}]

token = ""  # 做一个记录  标识登是否成功

count = 0


@app.route("/reg", methods=["GET", "POST"])
def reg():
    username = request.form.get("username")
    password = request.form.get("password")
    data = {"username": username, "password": password}
    user_list.append(data)

    return "注册成功"


@app.route("/login", methods=["GET", "POST"])
def login():
    username = request.form.get("username")
    password = request.form.get("password")

    for user in user_list:
        global token
        if user["username"] == username and user["password"] == password:
            token = "12222"
            # 重定向到列表
            return redirect("/bloglist")
        else:
            return "用户名或密码错误"


@app.route("/addblog", methods=["GET", "POST"])
def addblog():
    title = request.form.get("title")
    author = request.form.get("author")
    data = {"title": title, "author": author}
    blog_list.append(data)

    return "添加成功"


@app.route("/bloglist")
def bloglist():
    return jsonify(blog_list)


@app.route("/oneblog")
def oneblog():
    title = request.args.get("title")
    3 / 0
    global count
    count += 1
    for blog in blog_list:
        if blog["title"] == title:
            return jsonify(blog)

    return "没有这个标题的博客"


@app.errorhandler(404)
def handeler404(e):
    return "路径不存在，页面没有找到"


@app.errorhandler(500)
def handeler500(e):
    return "服务端错误"


@app.before_request
def before_request():
    print("开始请求")


@app.teardown_request
def after_request(e):  # 请求结束
    print("请求结束")


if __name__ == '__main__':
    app.run()
